package api

import (
	"Im/dao"
	"Im/dto"
	"Im/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

var upgrade = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
	return true
}}
var wc = make(map[any]*websocket.Conn)

func WebSocketMsg(c *gin.Context) {
	var conn *websocket.Conn
	var err error
	if c.GetHeader("sec-websocket-protocol") == "" {
		conn, err = upgrade.Upgrade(c.Writer, c.Request, nil)
	} else {
		conn, err = upgrade.Upgrade(c.Writer, c.Request, http.Header{"sec-websocket-protocol": {c.GetHeader("sec-websocket-protocol")}})
	}
	if err != nil {
		c.AbortWithStatusJSON(403, gin.H{
			"msg": "系统异常" + err.Error(),
		})
		fmt.Println(err.Error())
		return
	}
	uc := c.MustGet("user_claims").(utils.JwtCastClaims)
	wc[uc.UserId] = conn
	defer func() {
		//链接断开时接链接数据从map中删除用户的链接数据
		delete(wc, uc.UserId)
		conn.Close()
	}()
	for {
		_, message, err3 := conn.ReadMessage()
		if err3 != nil {
			log.Println(err3)
			return
		}
		ms := new(dto.Message)
		errJson := json.Unmarshal(message, ms)

		if errJson != nil {
			fmt.Println("这不是json文件")
			data := bytes.NewReader(message)
			utils.ImgCompress(data, "demo.png")
		} else {
			// TODO: 判断用户是否属于消息体的房间
			_, err = dao.GetUserRoomByUserIdRoomId(uc.UserId, ms.RoomId)
			if err != nil {
				log.Println(ms)
				log.Println("Read Error" + err.Error())
				return
			}
			//TODO: 保存消息
			err = dao.SaveUserMsg(uc.UserId, ms.RoomId, ms.Message)
			if err != nil {
				_ = conn.WriteMessage(websocket.TextMessage, []byte("服务器错误"+err.Error()))
			}
			//TODO: 获取特定房间的用户
			userRooms, err2 := dao.GetUserRoomByRoomId(ms.RoomId)
			if err2 != nil {
				log.Println(err2.Error())
				return
			}
			for _, room := range userRooms {
				//拿到用户的id
				if cc, ok := wc[room.UserId]; ok {
					err = cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
					if err != nil {
						fmt.Println(err.Error())
						return
					}
				}
			}
		}
	}
}
